import $state from '../state/index.js';
import Api from "@/api"
let timer = null

// #ifdef APP
const shortCutBadge = uni.requireNativePlugin('Ba-Shortcut-Badge')
// #endif

export default {
	async getList() {
		Api.chat.getChatList({
			pageNum: 1,
			pageSize: 1000
		}).then(res => {
			res.rows.forEach((item, index) => {
				item = this.handleData(item)
			})
			console.log('res.rows',res.rows)
			$state.chatList = res.rows
		}).catch(() => {
			let fn = (net) => {
				if (net.isConnected) {
					this.getList()
				}
			}
			uni.offNetworkStatusChange(fn)
			uni.onNetworkStatusChange(fn);
		})
	},
	async getNoMsg() {
		const res = await Api.chat.chatNoRead()
		$state.noReadNum = res.data
		if (res.data > 0) {
			uni.setTabBarBadge({
				index: 1,
				text: res.data > 99 ? '...' : String(res.data),
				color: '#F40' // 小红点的颜色
			});
			// #ifdef APP
			shortCutBadge.applyCount({
				'badgeCount': res.data
			});
			// #endif
		} else {
			uni.hideTabBarRedDot({
				index: 0,
			});
			// #ifdef APP
			shortCutBadge.clearCount();
			// #endif
		}
	},
	deepCopy(arr) {
		return arr.map(item => Array.isArray(item) ? deepCopy(item) : item);
	},
	removeChat(groupId) {
		let findIndex = $state.chatList.findIndex(item => {
			return item.groupId == groupId
		})
		$state.chatList.splice(findIndex, 1)
	},
	changeList(data) {
		if (data.lastMsg) {
			data = this.handleData(data)
		}
		
		let temChatList = this.deepCopy($state.chatList)
		
		let findIndex = temChatList.findIndex(item => {
			return item.groupId == data.groupId
		})
		
		if (findIndex != -1) {
			temChatList[findIndex] = {
				...$state.chatList[findIndex],
				...data
			}
		} else {
			temChatList.push(data)
		}

		let topArr = temChatList.filter(item => {
			return item.isTop == 1
		})

		let otherArr = temChatList.filter(item => {
			return item.isTop == 0
		})

		$state.chatList = [
			...topArr.sort((a, b) => {
				let dateA = new Date(a.realTime)
				let dateB = new Date(b.realTime)
				return dateB - dateA;
			}),
			...otherArr.sort((a, b) => {
				let dateA = new Date(a.realTime)
				let dateB = new Date(b.realTime)
				return dateB - dateA;
			}),
		]
	},
	handleData(item) {
		if ((item.msgContentType == 'text' || item.msgContentType == 'atText') && item.msgType == 1) {
			try {
				item.lastMsg = JSON.parse(item.lastMsg).text
			} catch (e) {
				item.lastMsg = item.lastMsg
			}
			try {
				item.lastMsg = item.lastMsg.replace(/<img/g,
					'<img style="width:18px;height:18px"');

				item.lastMsg = item.lastMsg.replace(/<p/g,
					'<p style="display: flex;align-items: center;flex-wrap: wrap;"'
				);
			} catch (e) {}
		}
		return item
	}
}